package com.carter.springframework.beans.factory.support;

import com.carter.springframework.beans.exception.BeanException;
import com.carter.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 普通实例化bean策略实现类
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy{
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor<?> constructor, Object[] args) throws BeanException {
        Class<?> clazz = beanDefinition.getBeanClass();
        try {
            if (constructor!=null){
                return constructor.newInstance(args);
            }else {
                return clazz.getDeclaredConstructor().newInstance();
            }
        } catch (InvocationTargetException|InstantiationException|IllegalAccessException|NoSuchMethodException e) {
            throw new BeanException("实例化bean失败",e);
        }

    }
}
